<template>
	<view class="edit_ed">
		<view class="logo_pic">
			<image
				class="icon_header"
				:src="updateUser.avatar"
				mode="aspectFit"
				v-if="updateUser.avatar"
				@click="lookPic(updateUser.avatar)"
			></image>
			<view class="icon_header" v-else>
				<uni-icons size="120" color="#007cff" type="contact"></uni-icons>
			</view>

			<!-- #ifdef APP-PLUS -->
			<view class="pic_editor" @click="onUpdateAvatarClick">修改头像</view>
			<!-- #endif -->

			<!-- #ifdef H5 || MP-WEIXIN -->
			<view class="pic_editor">
				修改头像
				<uni-file-picker
					limit="1"
					:del-icon="false"
					:auto-upload="false"
					:sizeType="['original', 'compressed']"
					:sourceType="['album', 'camera']"
					disable-preview
					@select="onsuccessImg"
					:imageStyles="imageStyles2"
					file-mediatype="image"
				></uni-file-picker>
			</view>
			<!-- #endif -->
		</view>
		<view class="input_ediit">
			<text>账号</text>
			<uni-easyinput
				disabled
				placeholderStyle="font-size:28rpx;"
				:value="store.getters.setProcessingTel"
				placeholder="请输入内容"
			></uni-easyinput>
			<text>用户名称</text>
			<uni-easyinput
				v-model="updateUser.name"
				placeholderStyle="font-size:28rpx;"
				type="text"
				placeholder="请输入内容"
			></uni-easyinput>
		</view>
		<view class="btn_edit">
			<button
				type="primary"
				class="onlogout"
				:class="{btn_bg: updateUser.name}"
				:disabled="!updateUser.name"
				@click="changeNameImg"
			>
				保存
			</button>
		</view>
	</view>
</template>

<script setup lang="ts">
	import {ref, reactive} from 'vue';
	import apiUser from '@/util/network_api/user.js';
	import store from '@/store_network/index.js';

	const imgfile = ref(null); //获取图片文件
	const updateUser = reactive({
		avatar: store.state.userInfo.avatar, //头像
		name: store.state.userInfo.name, //客户姓名
		nickname: '', //昵称
	});
	const imageStyles2 = ref({
		width: 70,
		height: 30,
	});
	// 预览图片
	const lookPic = (list) => {
		uni.previewImage({
			urls: [list],
		});
	};
	//修改头像
	const onsuccessImg = (img) => {
		imgfile.value = img;
		updateUser.avatar = img.tempFilePaths[0];
	};
	//保存
	const changeNameImg = async () => {
		try {
			//显示加载框
			uni.showLoading({
				title: '加载中',
				mask: true,
			});
			if (imgfile.value) {
				const avatarUploadResult = await apiUser.uploadAvatar({
					files: imgfile.value.tempFiles[0],
				});
				if (avatarUploadResult.code === 20000) {
					updateUser.avatar = avatarUploadResult.data.rows;
				} else {
					return;
				}
			}
			const updateUserInfoResult = await apiUser.updateUserInfo(updateUser);
			if (updateUserInfoResult.code === 20000) {
				uni.showToast({
					title: updateUserInfoResult.message,
					icon: 'none',
					duration: 3000,
					position: 'top',
				});
				uni.navigateTo({
					url: '/pages/pages_network/user/user',
				});
				// 获取用户信息
				await store.dispatch('getUpdataUser');
			}
			// 隐藏加载框
			uni.hideLoading();
		} catch (error) {
			uni.hideLoading();
		}
	};

	/**
	 * 修改头像点击事件，只有在APP端时才调用这个方法，因为要提示用户获取权限才能以通过应用市场的上架
	 */
	const onUpdateAvatarClick = () => {
		const Manifest = plus.android.importClass('android.Manifest');
		const MainActivity = plus.android.runtimeMainActivity();
		if (MainActivity.checkSelfPermission(Manifest.permission.CAMERA) === -1) {
			uni.showModal({
				title: '请允许我们使用相机权限',
				content:
					'允许“叮咚到家平台”在您使用该应用时访问您的相机吗？允许访问才能拍摄图片用于更改头像',
				mask: true,
				icon: 'none',
				showCancel: true,
				cancelText: '我知道了',
				confirmText: '前往设置',
				success: (res) => {
					if (res.confirm) {
						uni.openAppAuthorizeSetting();
					}
				},
			});
			return;
		}

		if (
			MainActivity.checkSelfPermission(
				Manifest.permission.READ_EXTERNAL_STORAGE,
			) === -1
		) {
			uni.showModal({
				title: '请允许我们获取相册权限',
				content:
					'允许“叮咚到家平台”在您使用该应用时访问您的相册吗？允许访问才能获取您相册的图片用于更改头像',
				mask: true,
				icon: 'none',
				showCancel: true,
				cancelText: '我知道了',
				confirmText: '前往设置',
				success: (res) => {
					if (res.confirm) {
						uni.openAppAuthorizeSetting();
					}
				},
			});
			return;
		}

		uni.showActionSheet({
			itemList: ['拍摄', '从相册选择'],
			success: (res: {tapIndex: number}) => {
				if (res.tapIndex === 0) {
					uni.chooseImage({
						count: 1,
						sourceType: ['camera'],
						success: (res: {
							tempFiles: Array<File>;
							tempFilePaths: Array<string>;
						}) => {
							plus.io.resolveLocalFileSystemURL(
								res.tempFiles[0].path,
								(entry) => {
									entry.file(function (file) {
										imgfile.value = {
											tempFiles: [{...file, path: res.tempFiles[0].path}],
										};
									});
								},
								(err) => {
									// err
								},
							);
							updateUser.avatar = res.tempFilePaths[0];
						},
					});
				} else {
					uni.chooseImage({
						count: 1,
						sourceType: ['album'],
						success: (res: {
							tempFiles: Array<File>;
							tempFilePaths: Array<string>;
						}) => {
							plus.io.resolveLocalFileSystemURL(
								res.tempFiles[0].path,
								(entry) => {
									entry.file(
										(file) => {
											imgfile.value = {
												tempFiles: [{...file, path: res.tempFiles[0].path}],
											};
										},
										(error) => {
											// console.log(error);
										},
									);
								},
								(err) => {
									// err
								},
							);
							updateUser.avatar = res.tempFilePaths[0];
						},
					});
				}
			},
		});
	};
</script>

<style lang="scss">
	.edit_ed {
		.logo_pic {
			display: flex;
			align-items: center;
			justify-content: center;
			flex-direction: column;
			padding-top: 40rpx;

			:deep(.uni-file-picker__container) {
				justify-content: center;
			}

			.pic_editor {
				position: relative;
				color: #007cff;
				margin-top: 20rpx;
				font-size: 28rpx;

				:deep(.uni-file-picker) {
					opacity: 0;
					position: absolute;
					top: 0;
				}
			}

			.icon_header {
				width: 140rpx;
				height: 140rpx;
				border-radius: 50%;
				display: flex;
				align-items: center;
				justify-content: center;
				overflow: hidden;
				background-color: #ebf9ff;
			}
		}

		.input_ediit {
			margin: 0 60rpx;
			font-size: 28rpx;

			:deep(.is-input-border) {
				border-radius: 10rpx !important;
				background-color: rgba(243, 244, 248, 1) !important;
				padding: 10rpx;
				margin-bottom: 30rpx;
				margin-top: 10rpx;
				border: 0rpx solid #999;
				height: 80rpx;

				&.is-focused {
					.uniui-clear,
					.uniui-eye-filled {
						color: #007cff99 !important;
					}
				}
			}
		}

		.btn_edit {
			position: absolute;
			margin: 60rpx auto;
			width: 100%;

			:deep(button:after) {
				border: none !important;
			}

			.onlogout {
				font-size: 28rpx;
				font-weight: bold;
				margin: 0 60rpx;
				height: 80rpx;
				border-radius: 50rpx;
				line-height: 80rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				background-color: #007cff6b;
			}

			.btn_bg {
				background-color: #007cff;
			}
		}
	}
</style>
